#!/home1/tomorrp1/bin/python2.7
# -*- coding: utf-8 -*-
'''
Created on 2011-4-25

@author: sevear(sevear@gmail.com)
'''
import web
import model;
import json
import errconst;
import contact2,recommend,invite,event,p2p;
import os;
import util;
import chaosdb;
import datetime,time;

urls = (
	'/?',			  'DouChaos',
	'/login/?',		  'DBAuth',
	'/r/?',			  'recommend.Recommend',
	'/c/?',			  'contact2.Contacts2',
	'/t/?',			  'Track',
	'/invite/?',	  'invite.Invite',
	'/e/?',			  'event.Event',
	'/p2p/?',		  'p2p.P2pFM')

class DouChaos:
	def GET(self):
		i = web.input();
		if hasattr(i, "uid"):
			uid = web.input().uid;
			web.header('Content-Type', 'application/json')
			if hasattr(i, "time"):
				timesec= float(i.time);
				startDate = datetime.datetime.fromtimestamp(timesec);
			else:
				startDate = datetime.datetime.fromtimestamp(time.time());
			return json.dumps(model.getRecommendList(int(uid),startDate.strftime("%Y-%m-%d %H:%M:%S")),False,False,True,False)
		else:
			return errconst.GET_RECOMMEND_LIST_WITHOUT_UID;

class DBAuth:
	def POST(self):
		i = web.input();
		if hasattr(i, 'version') == False:
			return util.generateErr(errconst.LOGIN_WITHOUT_VERSION);
		else:
			if(util.checkVersion(i.version)==False):
				return util.generateErr(errconst.CLIENT_VERSION_TOO_OLD);
			else:
				if hasattr(i, "uid") and hasattr(i, "name") and hasattr(i, "url") and hasattr(i, 'alias') and hasattr(i, 'headimg'):
					model.registerUser(int(i.uid),i.name,i.url,i.alias,i.headimg,i.version);
					rst = {"errcode":0,"errmsg":"ok","content":""}
					return json.dumps(rst);
				elif hasattr(i,"userinfo"):
					info = json.loads(i.userinfo);
					model.registerUser(info["uid"],info["name"],info["url"],info["alias"],
									info["headimg"],info["version"]);
					rst = {"errcode":0,"errmsg":"ok","content":""}
					return json.dumps(rst);
				else:
					return util.generateErr(errconst.LOGIN_WITHOUT_FULL_INFO);
		
	
	def GET(self):
		i = web.input();
		if hasattr(i, "uid"):
			uid = web.input().uid;
			web.header('Content-Type', 'application/json');
			dbUser = model.getUser(int(uid));
			return json.dumps({'uid':dbUser[0].uid,
								'alias':dbUser[0].dbuid,
								'activietime':dbUser[0].activietime,
								'dburl':dbUser[0].dburl,
								'name':dbUser[0].name});
		else:
			return errconst.GET_USER_INFO_WITHOUT_UID;

class Logout:
	def POST(self):
		i = web.input();
		if hasattr(i, "uid"):
			uid = web.input().uid;
			if hasattr(i, "reids"):
				reids=i.reids.splice("|");
	
class Track:
	def GET(self):
		i = web.input();
		if hasattr(i, "sid"):
			sid = int(i.sid);
			track = chaosdb.getTrack(sid);
			if(track!=None):
				return json.dumps(track);
			
#web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr)
os.environ['TZ'] = 'Asia/Shanghai';
if __name__ == "__main__": 
	web.config.debug = True
	app = web.application(urls, globals());
	app.run();
